﻿using MixingStation.LTWebService;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MixingStation
{
    public partial class LocalWeightInfoForm : Form
    {
        //选择的物料编码
        private string m_MaterialCode = "";
        //选择的供应商编码
        private string m_SupplierCode = "";
        //选择的产地编码
        private string m_PlaceCode = "";
        //选择的流向编码
        private string m_DirectionCode = "";
        //打印状态
        private PrintedEnum m_Printed = PrintedEnum.All;
        //完结状态
        private StatusEnum m_Status = StatusEnum.All;
        //物资类型，0全部，1采购，2非采购
        private int m_WeightType = 0;
        //上传状态
        private UploadedEnum m_Uploaded = UploadedEnum.All;
        //是否退货,0全部，1是，2否
        private int m_Back = 0;

        //绑定DataTable
        private DataTable m_BindDT = null;
        //车辆所属公司
        private int m_BelongCorpId = 2;
        //记录订单编号与订单的字典
        private Dictionary<string, purchaseOrderWS> m_PurchaseOrderDic = new Dictionary<string, purchaseOrderWS>();

        private List<materialWS> m_MaterialList = new List<materialWS>();
        public List<materialWS> MaterialList
        {
            set { m_MaterialList = value; }
        }
        private List<supplierWS> m_SupplierList = new List<supplierWS>();
        public List<supplierWS> SupplierList
        {
            set { m_SupplierList = value; }
        }
        private List<placeWS> m_PlaceList = new List<placeWS>();
        public List<placeWS> PlaceList
        {
            set { m_PlaceList = value; }
        }
        private List<DirectionInfo> m_DirectionList = new List<DirectionInfo>();
        public List<DirectionInfo> DirectionList
        {
            set { m_DirectionList = value; }
        }
        public LocalWeightInfoForm()
        {
            InitializeComponent();
        }

        private void WeightInfoForm_Load(object sender, EventArgs e)
        {
            this.Size = Screen.GetWorkingArea(this).Size;
            this.Location = new Point(0, 0);
            m_BelongCorpId = int.Parse(ConfigurationManager.AppSettings["BelongCorpId"]);
            InitBinDT();
            InitCmbMaterial();
            InitCmbSupplier();
            InitCmbPlace();
            InitCmbDirection();

            InitCmbPrinted();
            InitCmbStatus();
            InitCmbcmbUploadStatus();
            InitCmbWeightType();
            InitCmbIsBack();
            InitDateTime();
        }

        #region 初始化
        //初始化物料下拉框
        private void InitCmbMaterial()
        {
            try
            {
                if (m_MaterialList == null || m_MaterialList.Count == 0)
                    return;
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = "", Value = "" });
                foreach (materialWS material in m_MaterialList)
                    list.Add(new DataInfo { Id = material.code, Value = material.name });
                cmbMaterial.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbMaterial.Properties.Items.Add(item);
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化物料下拉框异常：" + ex.ToString());
            }
        }

        //初始化供应商下拉框
        private void InitCmbSupplier()
        {
            try
            {
                if (m_SupplierList == null || m_SupplierList.Count == 0)
                    return;
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = "", Value = "" });
                foreach (supplierWS supplier in m_SupplierList)
                    list.Add(new DataInfo { Id = supplier.code, Value = supplier.name });
                cmbSupplier.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbSupplier.Properties.Items.Add(item);
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化供应商下拉框异常：" + ex.ToString());
            }
        }

        //初始化产地下拉框
        private void InitCmbPlace()
        {
            try
            {
                if (m_PlaceList == null || m_PlaceList.Count == 0)
                    return;
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = "", Value = "" });
                foreach (placeWS place in m_PlaceList)
                    list.Add(new DataInfo { Id = place.code, Value = place.name });
                cmbPlace.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbPlace.Properties.Items.Add(item);
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化产地下拉框异常：" + ex.ToString());
            }
        }

        //初始化流向下拉框
        private void InitCmbDirection()
        {
            try
            {
                if (m_DirectionList == null || m_DirectionList.Count == 0)
                    return;
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = "", Value = "" });
                foreach (DirectionInfo direction in m_DirectionList)
                    list.Add(new DataInfo { Id = direction.Code, Value = direction.Name });
                cmbDirection.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbDirection.Properties.Items.Add(item);
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化流向下拉框异常：" + ex.ToString());
            }
        }

        //初始化是否打印下拉框
        private void InitCmbPrinted()
        {
            try
            {
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = ((int)PrintedEnum.All).ToString(), Value = "全部" });
                list.Add(new DataInfo { Id = ((int)PrintedEnum.UnPrinted).ToString(), Value = "未打印" });
                list.Add(new DataInfo { Id = ((int)PrintedEnum.Printed).ToString(), Value = "已打印" });
                cmbPrinted.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbPrinted.Properties.Items.Add(item);
                cmbPrinted.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化打印状态下拉框异常：" + ex.ToString());
            }
        }

        //初始化状态下拉框
        private void InitCmbStatus()
        {
            try
            {
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = ((int)StatusEnum.All).ToString(), Value = "全部" });
                list.Add(new DataInfo { Id = ((int)StatusEnum.UnCompleted).ToString(), Value = "未完结" });
                list.Add(new DataInfo { Id = ((int)StatusEnum.Completed).ToString(), Value = "完结" });
                cmbStatus.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbStatus.Properties.Items.Add(item);
                cmbStatus.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化装车状态下拉框异常：" + ex.ToString());
            }
        }

        //初始化上传状态下拉框
        private void InitCmbcmbUploadStatus()
        {
            try
            {
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = ((int)UploadedEnum.All).ToString(), Value = "全部" });
                list.Add(new DataInfo { Id = ((int)UploadedEnum.UnUploaded).ToString(), Value = "未上传" });
                list.Add(new DataInfo { Id = ((int)UploadedEnum.FirstUploaded).ToString(), Value = "第一次称重已上传" });
                cmbUploadStatus.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbUploadStatus.Properties.Items.Add(item);
                cmbUploadStatus.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化上传状态下拉框异常：" + ex.ToString());
            }
        }

        //初始化物资类型下拉框
        private void InitCmbWeightType()
        {
            try
            {
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = (0).ToString(), Value = "全部" });
                list.Add(new DataInfo { Id = (1).ToString(), Value = "采购" });
                list.Add(new DataInfo { Id = (2).ToString(), Value = "非采购" });
                cmbWeightType.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbWeightType.Properties.Items.Add(item);
                cmbWeightType.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化物资类型下拉框异常：" + ex.ToString());
            }
        }

        //初始化是否退货下拉框
        private void InitCmbIsBack()
        {
            try
            {
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = (0).ToString(), Value = "全部" });
                list.Add(new DataInfo { Id = (1).ToString(), Value = "是" });
                list.Add(new DataInfo { Id = (2).ToString(), Value = "否" });
                cmbIsBack.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbIsBack.Properties.Items.Add(item);
                cmbIsBack.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化是否退货下拉框异常：" + ex.ToString());
            }
        }

        //初始化时间
        private void InitDateTime()
        {
            DateTime current = DateTime.Now;
            fromFirstTime.EditValue = new DateTime(current.Year, current.Month, current.Day, 0, 0, 0);
            toFirstTime.EditValue = new DateTime(current.Year, current.Month, current.Day, 23, 59, 59);
            fromLastTime.EditValue = new DateTime(current.Year, current.Month, current.Day, 0, 0, 0);
            toLastTime.EditValue = new DateTime(current.Year, current.Month, current.Day, 23, 59, 59);
        }

        //初始化绑定的DT
        private void InitBinDT()
        {
            m_BindDT = new DataTable();
            m_BindDT.Columns.Add("Id");
            m_BindDT.Columns.Add("SystemId");
            m_BindDT.Columns.Add("OrderCode");
            m_BindDT.Columns.Add("CarCode");
            m_BindDT.Columns.Add("MaterialCode");
            m_BindDT.Columns.Add("Material");
            m_BindDT.Columns.Add("SupplierCode");
            m_BindDT.Columns.Add("Supplier");
            m_BindDT.Columns.Add("PlaceCode");
            m_BindDT.Columns.Add("Place");
            m_BindDT.Columns.Add("DirectionCode");
            m_BindDT.Columns.Add("Direction");
            m_BindDT.Columns.Add("ReceiveCode");
            m_BindDT.Columns.Add("Receive");
            m_BindDT.Columns.Add("TempWeight");
            m_BindDT.Columns.Add("GrossWeight");
            m_BindDT.Columns.Add("Tareweight");
            m_BindDT.Columns.Add("BuckleWeight");
            m_BindDT.Columns.Add("BuckleReasons");
            m_BindDT.Columns.Add("NetWeight");
            m_BindDT.Columns.Add("DeliveryWeight");
            m_BindDT.Columns.Add("FirstWeightTime");
            m_BindDT.Columns.Add("FirstWeightMan");
            m_BindDT.Columns.Add("LastWeightTime");
            m_BindDT.Columns.Add("LastWeightMan");
            m_BindDT.Columns.Add("Status");
            m_BindDT.Columns.Add("Printed");
            m_BindDT.Columns.Add("UploadStatus");
            m_BindDT.Columns.Add("IsPurchase");
            m_BindDT.Columns.Add("IsBack");
            m_BindDT.Columns.Add("Remark");
        }
        #endregion

        #region 按钮事件
        private void btnSearch_Click(object sender, EventArgs e)
        {
            Search();
        }

        //数据上传
        private void btnUpload_Click(object sender, EventArgs e)
        {
            if (GV_loadInfos.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择数据!");
                return;
            }
            //数据上传时需在联网状态下，采购物资上传时需选择订单，非采购物资无需选择订单
            // 未完结上传
            //1、上传状态为未上传，
            //完结上传
            //1、若上传状态为第一次称重已上传
            //2、若上传状态为未上传，
            using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
            {
                bool isOnline = ServerCommonHelper.IsWebServiceAvaiable(client.Endpoint.Address.Uri);
                if (!isOnline)
                {
                    MessageBox.Show("离线状态下无法上传数据！");
                    return;
                }
                AdminConfirmForm adminForm = new AdminConfirmForm();
                adminForm.IsOnline = isOnline;
                adminForm.UserType = "管理员";
                if (adminForm.ShowDialog() != DialogResult.OK)
                    return;
                long id = long.Parse(GV_loadInfos.SelectedRows[0].Cells["IdColumn"].Value.ToString());
                WeightRecordInfo weightRecordInfo = ServerCommonHelper.ConvertWeightRecordInfoByRow(GV_loadInfos.SelectedRows[0]);
                if (weightRecordInfo.IsPurchase)
                {
                    purchaseOrderWS purchaseOrder = null;
                    if (!weightRecordInfo.IsCompleted)
                    {
                        if (m_PurchaseOrderDic.ContainsKey(weightRecordInfo.OrderCode))
                            purchaseOrder = m_PurchaseOrderDic[weightRecordInfo.OrderCode];
                        if (purchaseOrder == null)
                        {
                            MessageBox.Show("上传采购物资数据请先选择订单!");
                            return;
                        }
                        weightRecordInfo.PurchaseOrder = purchaseOrder;
                        carWS car = ServerCommonHelper.GetCar(weightRecordInfo.CarCode, 2, m_BelongCorpId);
                        //这种情况在勾选时需让他选择订单，这里无需判断
                        purchaseCardWS purchaseCard = ServerCommonHelper.CreatePurchaseCard(car, adminForm.User, weightRecordInfo);
                        ServerCommonHelper.SavePurchaseCard(purchaseCard);
                    }
                    else
                    {
                        if (weightRecordInfo.UploadStatus == (int)UploadedEnum.UnUploaded)
                        {
                            if (m_PurchaseOrderDic.ContainsKey(weightRecordInfo.OrderCode))
                                purchaseOrder = m_PurchaseOrderDic[weightRecordInfo.OrderCode];
                            if (purchaseOrder == null)
                            {
                                MessageBox.Show("上传采购物资数据请先选择订单!");
                                return;
                            }
                            weightRecordInfo.PurchaseOrder = purchaseOrder;
                            purchaseCardWS purchaseCard = ServerCommonHelper.CreatePurchaseCardByRecord(adminForm.User, m_BelongCorpId, weightRecordInfo);
                            ServerCommonHelper.UploadPurchaseCards(new purchaseCardWS[] { purchaseCard });
                        }
                        else if (weightRecordInfo.UploadStatus == (int)UploadedEnum.FirstUploaded)
                        {
                            purchaseCardWS purchaseCard = ServerCommonHelper.GetPurchaseCard(weightRecordInfo.CarCode);
                            if (purchaseCard == null)
                            {
                                MessageBox.Show("未获取" + weightRecordInfo.CarCode + "采购信息，详细信息请参考日志文件!");
                                return;
                            }
                            ServerCommonHelper.UpdatePurchaseCard(adminForm.User, weightRecordInfo, ref purchaseCard);

                            bool isSuccessful = ServerCommonHelper.SavePurchaseCard(purchaseCard);
                            if (!isSuccessful)
                            {
                                MessageBox.Show("上传数据失败，详细信息请参考日志文件!");
                                return;
                            }
                            //完结再保存一次
                            purchaseCard.cardState = 4;
                            isSuccessful = ServerCommonHelper.SavePurchaseCard(purchaseCard);
                            if (!isSuccessful)
                            {
                                MessageBox.Show("上传数据后完结失败，详细信息请参考日志文件!");
                                return;
                            }
                        }

                    }
                }
                else
                {
                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    //第一次有网保存的数据第二次无网修改，若两次都无网则插入
                    if (weightRecordInfo.UploadStatus == (int)UploadedEnum.UnUploaded)
                    {
                        if (!weightRecordInfo.IsCompleted)
                        {
                            dic.Add("carCode", weightRecordInfo.CarCode);
                            dic.Add("materialCode", weightRecordInfo.MaterialCode);
                            dic.Add("materialName", weightRecordInfo.MaterialName);
                            dic.Add("supplierCode", weightRecordInfo.SupplierCode);
                            dic.Add("supplierName", weightRecordInfo.SupplierName);
                            dic.Add("placeCode", weightRecordInfo.PlaceCode);
                            dic.Add("placeName", weightRecordInfo.PlaceName);
                            dic.Add("directionCode", weightRecordInfo.DirectionCode);
                            dic.Add("directionName", weightRecordInfo.DirectionName);
                            dic.Add("receiveCode", weightRecordInfo.ReceiveCode);
                            dic.Add("receive", weightRecordInfo.ReceiveName);
                            dic.Add("tempWeight", weightRecordInfo.TempWeight);
                            dic.Add("firstWeightTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            dic.Add("firstWeightMan", adminForm.User.employeeName);
                            dic.Add("remark", weightRecordInfo.Remark);
                            dic.Add("isCompleted", 0);
                            dic.Add("belongCorpId", m_BelongCorpId);
                        }
                        else
                        {
                            dic.Add("cardCode", weightRecordInfo.CarCode);
                            dic.Add("materialCode", weightRecordInfo.MaterialCode);
                            dic.Add("materialName", weightRecordInfo.MaterialName);
                            dic.Add("supplierCode", weightRecordInfo.SupplierCode);
                            dic.Add("supplierName", weightRecordInfo.SupplierName);
                            dic.Add("placeCode", weightRecordInfo.PlaceCode);
                            dic.Add("placeName", weightRecordInfo.PlaceName);
                            dic.Add("directionCode", weightRecordInfo.DirectionCode);
                            dic.Add("directionName", weightRecordInfo.DirectionName);
                            dic.Add("receiveCode", weightRecordInfo.ReceiveCode);
                            dic.Add("receive", weightRecordInfo.ReceiveName);
                            dic.Add("tempWeight", weightRecordInfo.TempWeight);
                            dic.Add("grossWeight", weightRecordInfo.GrossWeight);
                            dic.Add("tareWeight", weightRecordInfo.TareWeight);
                            dic.Add("buckleWeight", weightRecordInfo.BuckleWeight);
                            dic.Add("buckleReasons", weightRecordInfo.BuckleReasons);
                            dic.Add("netWeight", weightRecordInfo.NetWeight);
                            dic.Add("firstWeightTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            dic.Add("firstWeightMan", adminForm.User.employeeName);
                            dic.Add("lastWeightTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            dic.Add("lastWeightMan", adminForm.User.employeeName);
                            dic.Add("remark", weightRecordInfo.Remark);
                            dic.Add("isCompleted", 1);
                            dic.Add("belongCorpId", m_BelongCorpId);
                        }
                    }
                    else if (weightRecordInfo.UploadStatus == (int)UploadedEnum.FirstUploaded)
                    {
                        dic.Add("id", weightRecordInfo.SystemId);
                        dic.Add("materialCode", weightRecordInfo.MaterialCode);
                        dic.Add("materialName", weightRecordInfo.MaterialName);
                        dic.Add("supplierCode", weightRecordInfo.SupplierCode);
                        dic.Add("supplierName", weightRecordInfo.SupplierName);
                        dic.Add("placeCode", weightRecordInfo.PlaceCode);
                        dic.Add("placeName", weightRecordInfo.PlaceName);
                        dic.Add("directionCode", weightRecordInfo.DirectionCode);
                        dic.Add("directionName", weightRecordInfo.DirectionName);
                        dic.Add("receiveCode", weightRecordInfo.ReceiveCode);
                        dic.Add("receive", weightRecordInfo.ReceiveName);
                        dic.Add("grossWeight", weightRecordInfo.GrossWeight);
                        dic.Add("tareWeight", weightRecordInfo.TareWeight);
                        dic.Add("buckleWeight", weightRecordInfo.BuckleWeight);
                        dic.Add("buckleReasons", weightRecordInfo.BuckleReasons);
                        dic.Add("netWeight", weightRecordInfo.NetWeight);
                        dic.Add("lastWeightTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        dic.Add("lastWeightMan", adminForm.User.employeeName);
                        dic.Add("remark", weightRecordInfo.Remark);
                        dic.Add("isCompleted", 1);
                    }
                    long systemId = -1;  
                    CGlobal.strSwapJsonData = JsonConvert.SerializeObject(dic);
                    try
                    {
                        systemId = ServerCommonHelper.SaveWeightRecords(adminForm.User.userame, adminForm.User.password);
                        if (systemId == -1)
                        {
                            MessageBox.Show("上传数据后完结失败，详细信息请参考日志文件!");
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("上传数据后完结异常：" + ex.Message);
                        LogHelper.error("上传数据后完结异常:" + ex.Message);
                        return;
                    }
                     //若完结则插入，反之若未完结，则需更新本地数据SystemId
                    if (!weightRecordInfo.IsCompleted)
                    {
                        string sql = "update WeightRecords set SystemId = " + systemId + " where Id = " + id;
                        if (!CommonHelper.DoOpreation(sql))
                        {
                            LogHelper.error("非采购物资未完结数据上传后更新本地系统Id执行SQL" + sql + "失败");
                            MessageBox.Show("非采购物资未完结数据上传后更新本地系统Id失败,详细信息请参考日志文件!");
                            return;
                        }
                    }
                }
                if (weightRecordInfo.IsCompleted)
                {
                    //删除本地数据
                    string sql = "delete * from WeightRecords where Id = " + id;
                    if (!CommonHelper.DoOpreation(sql))
                    {
                        LogHelper.error("完结数据上传后删除本地数据时执行SQL" + sql + "失败");
                        MessageBox.Show("完结数据上传后删除本地数据失败,详细信息请参考日志文件!");
                        return;
                    }
                }
                MessageBox.Show("上传数据成功!");
            }
            Search();
        }

        //修改毛重
        private void btnModifyGross_Click(object sender, EventArgs e)
        {
            if (GV_loadInfos.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择数据!");
                return;
            }
            long id = long.Parse(GV_loadInfos.SelectedRows[0].Cells["IdColumn"].Value.ToString());
            WeightRecordInfo weightRecordInfo = ServerCommonHelper.ConvertWeightRecordInfoByRow(GV_loadInfos.SelectedRows[0]);

            try
            {
                using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
                {
                    bool isOnline = ServerCommonHelper.IsWebServiceAvaiable(client.Endpoint.Address.Uri);

                    if (weightRecordInfo.UploadStatus == (int)UploadedEnum.FirstUploaded && !isOnline)
                    {
                        MessageBox.Show("离线状态下无法修改第一次称重已上传数据!");
                        return;
                    }
                    AdminConfirmForm adminForm = new AdminConfirmForm();
                    adminForm.IsOnline = isOnline;
                    adminForm.UserType = "管理员";
                    if (adminForm.ShowDialog() != DialogResult.OK)
                        return;
                    WeightModifyForm form = new WeightModifyForm(WeightModifyType.Gross);
                    form.CarCode = weightRecordInfo.CarCode;
                    form.OriginWeight = (int)weightRecordInfo.GrossWeight;
                    if (form.ShowDialog() != DialogResult.OK)
                        return;
                    if (weightRecordInfo.UploadStatus == (int)UploadedEnum.FirstUploaded && isOnline)
                    {
                        if (weightRecordInfo.IsPurchase)
                        {
                            purchaseCardWS purchaseCard = ServerCommonHelper.GetPurchaseCard(weightRecordInfo.CarCode);
                            if (purchaseCard == null)
                            {
                                MessageBox.Show("未获取" + weightRecordInfo.CarCode + "采购信息，详细信息请参考日志文件!");
                                return;
                            }
                            purchaseCard.grossWeight = form.NewWeight;
                            purchaseCard.grossWeightSpecified = true;
                            purchaseCard.userId = Convert.ToInt64(adminForm.User.id);
                            purchaseCard.userIdSpecified = true;

                            bool isSuccessful = ServerCommonHelper.UploadPurchaseCards(new purchaseCardWS[] { purchaseCard });
                            if (!isSuccessful)
                            {
                                MessageBox.Show("修改毛重失败，详细信息请参考日志文件!");
                                return;
                            }
                        }
                        else
                        {
                            Dictionary<string, object> dic = new Dictionary<string, object>();
                            dic.Add("id", weightRecordInfo.SystemId);
                            dic.Add("grossWeight", form.NewWeight);
                            CGlobal.strSwapJsonData = JsonConvert.SerializeObject(dic);
                            try
                            {
                                long systemId = ServerCommonHelper.SaveWeightRecords(adminForm.User.userame, adminForm.User.password);
                                if (systemId == -1)
                                {
                                    MessageBox.Show("修改毛重失败，详细信息请参考日志文件!");
                                    return;
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("修改毛重异常：" + ex.Message);
                                LogHelper.error("修改毛重异常：" + ex.Message);
                                return;
                            }         
                        }
                    }
                    //只修改本地数据
                    if (weightRecordInfo.UploadStatus == (int)UploadedEnum.UnUploaded ||
                        weightRecordInfo.UploadStatus == (int)UploadedEnum.FirstUploaded)
                    {
                        string sql = "update WeightRecords set GrossWeight = " + form.NewWeight 
                            + " where Id = " + id;
                        if (!CommonHelper.DoOpreation(sql))
                        {
                            LogHelper.error("修改本地毛重数据时执行SQL" + sql + "失败");
                            MessageBox.Show("修改本地毛重数据失败,详细信息请参考日志文件!");
                            return;
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                LogHelper.error("修改毛重异常:" + ex.ToString());
                MessageBox.Show("修改毛重异常，详细信息请参考日志文件!");
                return;
            }
            MessageBox.Show("修改毛重成功!");
            Search();
        }

        //修改皮重
        private void btnModifyTare_Click(object sender, EventArgs e)
        {
            if (GV_loadInfos.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择数据!");
                return;
            }
            try
            {
                using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
                {
                    bool isOnline = ServerCommonHelper.IsWebServiceAvaiable(client.Endpoint.Address.Uri);
                    long id = long.Parse(GV_loadInfos.SelectedRows[0].Cells["IdColumn"].Value.ToString());
                    WeightRecordInfo weightRecordInfo = ServerCommonHelper.ConvertWeightRecordInfoByRow(GV_loadInfos.SelectedRows[0]);
                    //修改皮重必定是已完结状态，且上传状态为未上传，修改本地
                    if (!weightRecordInfo.IsCompleted && weightRecordInfo.TareWeight == 0)
                    {
                        MessageBox.Show("尚未称皮重，不能修改!");
                        return;
                    }
                    AdminConfirmForm adminForm = new AdminConfirmForm();
                    adminForm.IsOnline = isOnline;
                    adminForm.UserType = "管理员";
                    if (adminForm.ShowDialog() != DialogResult.OK)
                        return;
                    WeightModifyForm form = new WeightModifyForm(WeightModifyType.Tare);
                    form.CarCode = weightRecordInfo.CarCode;
                    form.OriginWeight = (int)weightRecordInfo.TareWeight;
                    if (form.ShowDialog() != DialogResult.OK)
                        return;

                    string sql = "update WeightRecords set TareWeight = " + form.NewWeight + " where Id = " + id;
                    if (!CommonHelper.DoOpreation(sql))
                    {
                        LogHelper.error("修改本地皮重数据时执行SQL" + sql + "失败");
                        MessageBox.Show("修改本地皮重数据失败,详细信息请参考日志文件!");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("修改皮重异常:" + ex.ToString());
                MessageBox.Show("修改皮重异常，详细信息请参考日志文件!");
                return;
            }
          
            MessageBox.Show("修改皮重成功!");
            Search();
        }

        private void btnModifyCarCode_Click(object sender, EventArgs e)
        {
            if (GV_loadInfos.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择数据!");
                return;
            }
            long id = long.Parse(GV_loadInfos.SelectedRows[0].Cells["IdColumn"].Value.ToString());
            WeightRecordInfo weightRecordInfo = ServerCommonHelper.ConvertWeightRecordInfoByRow(GV_loadInfos.SelectedRows[0]);

            try
            {
                using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
                {
                    bool isOnline = ServerCommonHelper.IsWebServiceAvaiable(client.Endpoint.Address.Uri);

                    if (weightRecordInfo.UploadStatus == (int)UploadedEnum.FirstUploaded && !isOnline)
                    {
                        MessageBox.Show("离线状态下无法修改第一次称重已上传数据!");
                        return;
                    }
                    AdminConfirmForm adminForm = new AdminConfirmForm();
                    adminForm.IsOnline = isOnline;
                    adminForm.UserType = "管理员";
                    if (adminForm.ShowDialog() != DialogResult.OK)
                        return;
                    CarCodeModifyForm form = new CarCodeModifyForm();
                    form.CarCode = weightRecordInfo.CarCode;
                    if (form.ShowDialog() != DialogResult.OK)
                        return;
                    if (weightRecordInfo.UploadStatus == (int)UploadedEnum.FirstUploaded && isOnline)
                    {
                        if (weightRecordInfo.IsPurchase)
                        {
                            purchaseCardWS purchaseCard = ServerCommonHelper.GetPurchaseCard(weightRecordInfo.CarCode);
                            if (purchaseCard == null)
                            {
                                MessageBox.Show("未获取" + weightRecordInfo.CarCode + "采购信息，详细信息请参考日志文件!");
                                return;
                            }
                            carWS car = ServerCommonHelper.GetCar(form.CarCode, 2, m_BelongCorpId);
                            if (car == null)
                            {
                                MessageBox.Show("修改车牌号失败，详细信息请参考日志文件!");
                                return;
                            }
                            purchaseCard.car = car;
                            purchaseCard.userId = Convert.ToInt64(adminForm.User.id);
                            purchaseCard.userIdSpecified = true;

                            bool isSuccessful = ServerCommonHelper.UploadPurchaseCards(new purchaseCardWS[] { purchaseCard });
                            if (!isSuccessful)
                            {
                                MessageBox.Show("修改车牌号失败，详细信息请参考日志文件!");
                                return;
                            }
                        }
                        else
                        {
                            Dictionary<string, object> dic = new Dictionary<string, object>();
                            dic.Add("id", weightRecordInfo.SystemId);
                            dic.Add("carCode", form.CarCode.TrimEnd('.'));
                            CGlobal.strSwapJsonData = JsonConvert.SerializeObject(dic);
                            try
                            {
                                long systemId = ServerCommonHelper.SaveWeightRecords(adminForm.User.userame, adminForm.User.password);
                                if (systemId == -1)
                                {
                                    MessageBox.Show("修改车牌号失败，详细信息请参考日志文件!");
                                    return;
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("修改车牌号异常：" + ex.Message);
                                LogHelper.error("修改车牌号异常：" + ex.Message);
                                return;
                            } 
                        }
                    }
                    //只修改本地数据
                    if (weightRecordInfo.UploadStatus == (int)UploadedEnum.UnUploaded 
                        || weightRecordInfo.UploadStatus == (int)UploadedEnum.FirstUploaded)
                    {
                        string sql = "update WeightRecords set CarCode = '" + form.CarCode.TrimEnd('.') + "' where Id = " + id;
                        if (!CommonHelper.DoOpreation(sql))
                        {
                            LogHelper.error("修改本地车牌号数据时执行SQL" + sql + "失败");
                            MessageBox.Show("修改本地车牌号数据失败,详细信息请参考日志文件!");
                            return;
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                LogHelper.error("修改车牌号异常:" + ex.ToString());
                MessageBox.Show("修改车牌号异常，详细信息请参考日志文件!");
                return;
            }
            MessageBox.Show("修改车牌号成功!");
            Search();
        }

        //导出Excel
        private void btnExportExcel_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "Export Excel File To";
            DialogResult dr = saveFileDialog.ShowDialog();

            if (dr == DialogResult.Cancel)
                return;
            Stream myStream = saveFileDialog.OpenFile();

            if (CommonHelper.ExportExcel(myStream, this.GV_loadInfos))
                MessageBox.Show("导出Excel成功！");
            else
                MessageBox.Show("导出Excel失败！");
        }

        private void btnReprint_Click(object sender, EventArgs e)
        {
            //本地待上传数据磅单补打只有完结且修改本地的
            if (GV_loadInfos.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择数据!");
                return;
            }
            long id = long.Parse(GV_loadInfos.SelectedRows[0].Cells["IdColumn"].Value.ToString());
            WeightRecordInfo weightRecordInfo = ServerCommonHelper.ConvertWeightRecordInfoByRow(GV_loadInfos.SelectedRows[0]);
            if (!weightRecordInfo.IsCompleted)
            {
                MessageBox.Show("称重尚未完结,无法打印！");
                return;
            }
            try
            {
                using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
                {
                    bool isOnline = ServerCommonHelper.IsWebServiceAvaiable(client.Endpoint.Address.Uri);
                    AdminConfirmForm adminForm = new AdminConfirmForm();
                    adminForm.IsOnline = isOnline;
                    adminForm.UserType = "管理员";
                    if (adminForm.ShowDialog() != DialogResult.OK)
                        return;

                    string sql = "select * from WeightRecords where id = " + id;
                    DataTable dt = DB2Helper.CreateInstance().DoDB2Select(sql);
                    if (dt == null || dt.Rows.Count == 0)
                    {
                        MessageBox.Show(this, "未获取到ID：" + weightRecordInfo.SystemId + "过磅记录！");
                        return;
                    }
                    WeightRecordInfo printInfo = CommonHelper.ConvertWeightRecordInfoByDataRow(dt.Rows[0]);
                    //打印
                    if (!CommonHelper.Print(printInfo, adminForm.User.employeeName))
                    {
                        MessageBox.Show(this, "磅单补打失败，详细信息请参考日志文件！");
                        return;
                    }
                    sql = "update WeightRecords set IsPrinted = " + true + " where Id = " + id;
                    if (!CommonHelper.DoOpreation(sql))
                    {
                        MessageBox.Show("磅单补打修改打印字段失败，详细信息请参考日志文件！");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("磅单补打异常：" + ex.ToString());
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }
        #endregion

        #region 下拉框事件
        //选择的物料
        private void cmbMaterial_SelectedIndexChanged(object sender, EventArgs e)
        {
          if (cmbMaterial.SelectedItem == null)
                m_MaterialCode = "";
          else
                m_MaterialCode = ((DataInfo)cmbMaterial.SelectedItem).Id;
        }

        //选择的供应商
        private void cmbSupplier_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSupplier.SelectedItem == null)
                m_SupplierCode = "";
            else
                m_SupplierCode = ((DataInfo)cmbSupplier.SelectedItem).Id;
        }

        //选择的产地
        private void cmbPlace_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbPlace.SelectedItem == null)
                m_PlaceCode = "";
            else
                m_PlaceCode = ((DataInfo)cmbPlace.SelectedItem).Id;
        }

        //选择的流向
        private void cmbDirection_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbDirection.SelectedItem == null)
                m_DirectionCode = "";
            else
                m_DirectionCode = ((DataInfo)cmbDirection.SelectedItem).Id;
        }

        //选择打印状态
        private void cmbPrinted_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbPrinted.SelectedItem == null || cmbPrinted.SelectedItem.ToString() == "")
            {
                cmbPrinted.SelectedIndex = 0;
                m_Printed = PrintedEnum.All;
            }
            else
            {
                string id = ((DataInfo)cmbPrinted.SelectedItem).Id;
                if (id == ((int)PrintedEnum.All).ToString())
                    m_Printed = PrintedEnum.All;
                else if (id == ((int)PrintedEnum.UnPrinted).ToString())
                    m_Printed = PrintedEnum.UnPrinted;
                else if (id == ((int)PrintedEnum.Printed).ToString())
                    m_Printed = PrintedEnum.Printed;
            }
        }

        //选择的上传状态
        private void cmbUploadStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbUploadStatus.SelectedItem == null || cmbUploadStatus.SelectedItem.ToString() == "")
            {
                cmbUploadStatus.SelectedIndex = 0;
                m_Uploaded = UploadedEnum.All;
            }
            else
            {
                string id = ((DataInfo)cmbUploadStatus.SelectedItem).Id;
                if (id == ((int)UploadedEnum.All).ToString())
                    m_Uploaded = UploadedEnum.All;
                else if (id == ((int)UploadedEnum.UnUploaded).ToString())
                    m_Uploaded = UploadedEnum.UnUploaded;
                else if (id == ((int)UploadedEnum.FirstUploaded).ToString())
                    m_Uploaded = UploadedEnum.FirstUploaded;
            }
        }

        //选择的装车状态
        private void cmbStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbStatus.SelectedItem == null || cmbStatus.SelectedItem.ToString() == "")
            {
                cmbStatus.SelectedIndex = 0;
                m_Status = StatusEnum.All;
            }
            else
            {
                string id = ((DataInfo)cmbStatus.SelectedItem).Id;
                if (id == ((int)StatusEnum.All).ToString())
                    m_Status = StatusEnum.All;
                else if (id == ((int)StatusEnum.UnCompleted).ToString())
                    m_Status = StatusEnum.UnCompleted;
                else if (id == ((int)StatusEnum.Completed).ToString())
                    m_Status = StatusEnum.Completed;
            }
        }

        //物资类型
        private void cmbWeightType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbWeightType.SelectedItem == null || cmbWeightType.SelectedItem.ToString() == "")
            {
                cmbWeightType.SelectedIndex = 0;
                m_WeightType = 0;
            }
            else
            {
                string id = ((DataInfo)cmbWeightType.SelectedItem).Id;
                m_WeightType = int.Parse(id);
            }
        }

        //退货
        private void cmbIsBack_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbIsBack.SelectedItem == null || cmbIsBack.SelectedItem.ToString() == "")
            {
                cmbIsBack.SelectedIndex = 0;
                m_Back = 0;
            }
            else
            {
                string id = ((DataInfo)cmbIsBack.SelectedItem).Id;
                m_Back = int.Parse(id);
            }
        }
        #endregion

        #region 查询
        private void Search()
        {
            try
            {
                string sql = CreateSearchSql();
                DataTable retDT = CommonHelper.DoSelectOpreation(sql);
                m_BindDT.Rows.Clear();
                if (retDT == null || retDT.Rows.Count == 0)
                {
                    this.txtRecordNum.Text = "0";
                    this.txtGrossTotal.Text = "0";
                    this.txtTareTotal.Text = "0";
                    this.txtNetTotal.Text = "0";
                    this.txtBuckleTotal.Text = "0";
                    return;
                }
                this.GV_loadInfos.DataSource = m_BindDT;
                BindData(retDT);
            }
            catch (Exception ex)
            {
                LogHelper.error("查询异常：" + ex.ToString());
                MessageBox.Show("查询异常,详细信息请参考日志文件!");
            }
        }

        //构建查询SQL语句
        private string CreateSearchSql()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("select s.*, t.Name as Material, u.Name as Supplier,  v.Name as Place,w.Name as Direction, x.Name as Receive from ");
            sb.AppendLine(" (((((WeightRecords s left join Material t on s.MaterialCode = t.Code)");
            sb.AppendLine(" left join Supplier u on s.SupplierCode = u.Code)");
            sb.AppendLine(" left join Place v on s.PlaceCode = v.Code)");
            sb.AppendLine(" left join Direction w on s.DirectionCode = w.Code)");
            sb.AppendLine(" left join Receive x on s.ReceiveCode = x.Code)");
            sb.AppendLine(" where 1 = 1");
            if (chkIsUseFirst.Checked)
            {
                DateTime startTime = this.fromFirstTime.DateTime;
                DateTime endTime = this.toFirstTime.DateTime;
                sb.AppendFormat(" and (FirstWeightTime >= #{0}# and FirstWeightTime <= #{1}#)",
                    startTime.ToString("yyyy-MM-dd HH:mm:ss"), endTime.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            if (chkIsUseLast.Checked)
            {
                DateTime startTime = this.fromLastTime.DateTime;
                DateTime endTime = this.toLastTime.DateTime;
                sb.AppendFormat(" and (LastWeightTime >= #{0}# and LastWeightTime <= #{1}#)",
                    startTime.ToString("yyyy-MM-dd HH:mm:ss"), endTime.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            if (!string.IsNullOrEmpty(txtCarCode.Text.Trim()))
            {
                sb.AppendFormat(" and CarCode like '%{0}%'", txtCarCode.Text.Trim());
            }
            if (!string.IsNullOrEmpty(m_MaterialCode))
            {
                sb.AppendFormat(" and MaterialCode = '{0}'", m_MaterialCode);
            }
            if (!string.IsNullOrEmpty(m_SupplierCode))
            {
                sb.AppendFormat(" and SupplierCode = '{0}'", m_SupplierCode);
            }
            if (!string.IsNullOrEmpty(m_PlaceCode))
            {
                sb.AppendFormat(" and PlaceCode = '{0}'", m_PlaceCode);
            }
            if (!string.IsNullOrEmpty(m_DirectionCode))
            {
                sb.AppendFormat(" and DirectionCode = '{0}'", m_DirectionCode);
            }
            if (m_Printed != PrintedEnum.All)
            {
                if (m_Printed == PrintedEnum.Printed)
                    sb.AppendLine(" and IsPrinted = True");
                else if (m_Printed == PrintedEnum.UnPrinted)
                    sb.AppendLine(" and IsPrinted = False");
            }
            //未完结状态且第一次称重已上传这种数据应查询不到
            if (m_Status != StatusEnum.All)
            {
                if (m_Status == StatusEnum.Completed)
                {
                    sb.AppendLine(" and ((IsCompleted = True and UploadStatus = " + (int)UploadedEnum.UnUploaded);
                    sb.AppendLine(" or (IsCompleted = True and UploadStatus = " + (int)UploadedEnum.FirstUploaded + "))");
                }
                else if (m_Status == StatusEnum.UnCompleted)
                    sb.AppendLine(" and IsCompleted = False and UploadStatus = " + (int)UploadedEnum.UnUploaded);
            }
            else
            {
                sb.AppendLine(" and ((IsCompleted = True and UploadStatus = " + (int)UploadedEnum.UnUploaded + ")");
                sb.AppendLine(" or (IsCompleted = True and UploadStatus = " + (int)UploadedEnum.FirstUploaded + ")");
                sb.AppendLine(" or (IsCompleted = False and UploadStatus = " + (int)UploadedEnum.UnUploaded + "))");
            }
            if (m_WeightType != 0)
            {
                bool isPurchase = m_WeightType == 1 ? true : false;
                sb.AppendLine(" and IsPurchase = " + isPurchase);
            }
            if (m_Back != 0)
            {
                bool isBack = m_Back == 1 ? true : false;
                sb.AppendLine(" and IsBack = " + isBack);
            }
            return sb.ToString();
        }

        //绑定列表
        private void BindData(DataTable retDT)
        {
            int id;
            int systemId;
            string orderCode = "";
            string carCode = "";
            string materialCode = "";
            string material = "";
            string supplierCode = "";
            string supplier = "";
            string placeCode = "";
            string place = "";
            string directionCode = "";
            string direction = "";
            string receiveCode = "";
            string receive = "";
            decimal tempWeight = 0;
            decimal grossWeight = 0;
            decimal tareWeight = 0;
            decimal buckleWeight = 0;
            string buckleReasons = "";
            decimal netWeight = 0;
            decimal deliveryWeight = 0;
            DateTime firstWeightTime;
            string firstWeightMan = "";
            DateTime lastWeightTime;
            string lastWeightMan = "";
            string status = "";
            string printed = "";
            string uploaded = "";
            string weightType = "";
            string isBack = "";
            string remark = "";

            int recordNum = 0;
            decimal grossWeightTotal = 0;
            decimal tareWeightTotal = 0;
            decimal buckleWeightTotal = 0;
            decimal netWeightTotal = 0;
            try
            {
                foreach (DataRow dr in retDT.Rows)
                {
                    id = int.Parse(dr["Id"].ToString());
                    systemId = int.Parse(dr["SystemId"].ToString());
                    orderCode = dr["OrderCode"].ToString();
                    carCode = dr["CarCode"].ToString();
                    materialCode = dr["MaterialCode"].ToString();
                    material = dr["Material"].ToString();
                    supplierCode = dr["SupplierCode"].ToString();
                    supplier = dr["Supplier"].ToString();
                    placeCode = dr["PlaceCode"].ToString();
                    place = dr["Place"].ToString();
                    directionCode = dr["DirectionCode"].ToString();
                    direction = dr["Direction"].ToString();
                    receiveCode = dr["ReceiveCode"].ToString();
                    receive = dr["Receive"].ToString();

                    tempWeight = dr["TempWeight"] == DBNull.Value ? 0 : int.Parse(dr["TempWeight"].ToString());
                    grossWeight = dr["GrossWeight"] == DBNull.Value ? 0 : int.Parse(dr["GrossWeight"].ToString());
                    tareWeight = dr["TareWeight"] == DBNull.Value ? 0 : int.Parse(dr["TareWeight"].ToString());
                    buckleWeight = dr["BuckleWeight"] == DBNull.Value ? 0 : int.Parse(dr["BuckleWeight"].ToString());
                    buckleReasons = dr["BuckleReasons"].ToString();

                    netWeight = grossWeight - tareWeight - buckleWeight;
                    deliveryWeight = dr["DeliveryWeight"] == DBNull.Value ? 0 : int.Parse(dr["DeliveryWeight"].ToString());

                    firstWeightTime = dr["FirstWeightTime"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(dr["FirstWeightTime"].ToString());
                    firstWeightMan = dr["FirstWeightMan"].ToString();
                    lastWeightTime = dr["LastWeightTime"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(dr["LastWeightTime"].ToString());
                    lastWeightMan = dr["LastWeightMan"].ToString();
         
                    printed = dr["IsPrinted"].ToString() == "True" ? "已打印" : "未打印";
                    status = dr["IsCompleted"].ToString() == "True" ? "完结" : "未完结";
                    int uploadStatus = int.Parse(dr["UploadStatus"].ToString());
                    uploaded = uploadStatus == (int)UploadedEnum.UnUploaded ? "未上传" :
                        (uploadStatus == (int)UploadedEnum.FirstUploaded ? "第一次称重已上传" : "已上传");

                    weightType = dr["IsPurchase"].ToString() == "True" ? "是" : "否";
                    isBack = dr["IsBack"].ToString() == "True" ? "是" : "否";
                    remark = dr["Remark"].ToString();

                    m_BindDT.Rows.Add(id, systemId, orderCode, carCode, materialCode, material, supplierCode, supplier, placeCode, place,
                        directionCode, direction, receiveCode, receive, tempWeight, grossWeight, tareWeight, buckleWeight, buckleReasons, netWeight, deliveryWeight,
                        firstWeightTime, firstWeightMan, lastWeightTime, lastWeightMan,
                        status, printed, uploaded, weightType, isBack, remark);

                    recordNum++;
                    grossWeightTotal += grossWeight;
                    tareWeightTotal += tareWeight;
                    buckleWeightTotal += buckleWeight;
                    netWeightTotal += netWeight;
                }
                this.GV_loadInfos.DataSource = m_BindDT;

                this.txtRecordNum.Text = recordNum.ToString();
                this.txtGrossTotal.Text = (grossWeightTotal / 1000).ToString();
                this.txtTareTotal.Text = (tareWeightTotal / 1000).ToString();
                this.txtNetTotal.Text = (netWeightTotal / 1000).ToString();
                this.txtBuckleTotal.Text = (buckleWeightTotal / 1000).ToString();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
        #endregion

        private void GV_loadInfos_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //点击选择订单的界面
            if (GV_loadInfos.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex > -1)
            {
                string materialCode = GV_loadInfos.Rows[e.RowIndex].Cells["MaterialCodeColumn"].Value.ToString();
                string supplierCode = GV_loadInfos.Rows[e.RowIndex].Cells["SupplierCodeColumn"].Value.ToString();
                PurchaseOrderSelectForm form = new PurchaseOrderSelectForm();
                form.MaterialArr = m_MaterialList.ToArray();
                form.SupplierArr = m_SupplierList.ToArray();
                form.MaterialCode = materialCode;
                form.SupplierCode = supplierCode;
                if (DialogResult.OK == form.ShowDialog())
                {
                    purchaseOrderWS purchaseOrder = form.SelectPurchaseOrder;
                    GV_loadInfos.Rows[e.RowIndex].Cells["OrderCodeColumn"].Value = purchaseOrder.code;
                    if (!m_PurchaseOrderDic.ContainsKey(purchaseOrder.code))
                        m_PurchaseOrderDic.Add(purchaseOrder.code, purchaseOrder);
                }
            }
        }

        //行号
        private void GV_loadInfos_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y,
                GV_loadInfos.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
            GV_loadInfos.RowHeadersDefaultCellStyle.Font, rectangle,
            GV_loadInfos.RowHeadersDefaultCellStyle.ForeColor,
            TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
    }
}
